package com.buddies.lottery.ui.lottery;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.blankj.utilcode.util.ConvertUtils;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseFragment;
import com.buddies.lottery.data.bean.Lottery;
import com.buddies.lottery.data.result.PageResult;
import com.buddies.lottery.ui.lottery.detail.LotteryDetailActivity;
import com.buddies.lottery.widget.OnTabClickListener;
import com.buddies.lottery.widget.SpaceItemDecoration;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

public class LotteryCategoryFragment extends BaseFragment<LotteryCategoryContract.Presenter> implements LotteryCategoryContract.View, OnTabClickListener {

    private SwipeRefreshLayout mSwipeRefreshLayout;

    private RecyclerView mRecyclerView;
    private GridLayoutManager mLayoutManager;
    private LotteryCategoryAdapter mAdapter;
    private List<Lottery> mItems = new ArrayList<>();
    private int mCategory;

    public static LotteryCategoryFragment newInstance(int category) {
        Bundle args = new Bundle();
        args.putSerializable("category", category);

        LotteryCategoryFragment fragment = new LotteryCategoryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null) {
            mCategory = args.getInt("category");
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_lottery_category;
    }

    @Override
    public void initView() {
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresher);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                forceRefresh();
            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    @Override
    public void initData() {
        mPresenter = new LotteryCategoryPresenter(this);

        mLayoutManager = new GridLayoutManager(getActivity(), 1, GridLayoutManager.VERTICAL, false);

        mAdapter = new LotteryCategoryAdapter(mItems);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                LotteryDetailActivity.launch(getActivity(), mItems.get(position));
            }
        });

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(ConvertUtils.dp2px(7)));
        mRecyclerView.setAdapter(mAdapter);
    }

    protected void forceRefresh() {
        if (mSwipeRefreshLayout != null) {
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(true);
                    mPresenter.loadLotteryList(mCategory);
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        forceRefreshIfNeed();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        forceRefreshIfNeed();
    }

    private boolean isUserVisible() {
        Fragment parent = getParentFragment();
        return getUserVisibleHint() && parent != null && ((LotteryFragment) parent).isUserVisible() && ((LotteryFragment) parent).getCurrentTab() == mCategory;
    }

    private void forceRefreshIfNeed() {
        if (isUserVisible()) {
            forceRefresh();
        }
    }

    @Override
    public void onLotteryListLoaded(PageResult<Lottery> response) {
        mSwipeRefreshLayout.setRefreshing(false);
        if (!mItems.isEmpty()) {
            mItems.clear();
        }
        if (response.list != null && !response.list.isEmpty()) {
            mItems.addAll(response.list);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onError(Throwable e) {
        super.onError(e);
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onTabClick() {
        if (mLayoutManager != null) {
            int currentPosition = mLayoutManager.findFirstCompletelyVisibleItemPosition();
            if (currentPosition == 0 || mItems.isEmpty()) {// 第一页
                forceRefresh();
            } else if (mRecyclerView != null) {
                if (currentPosition > 12) {
                    mRecyclerView.scrollToPosition(12);
                }
                mRecyclerView.smoothScrollToPosition(0);
            }
        }
    }

}
